<template>
  <el-dialog
    v-model="visible"
    title="添加新作业"
    width="600px"
    @close="resetForm"
  >
    <el-form
      ref="formRef"
      :model="form"
      :rules="rules"
      label-width="100px"
    >
      <el-form-item label="作业标题" prop="title">
        <el-input
          v-model="form.title"
          placeholder="请输入作业标题（如留空将使用默认标题）"
        />
        <div class="form-tip">默认标题：{{ defaultTitle }}</div>
      </el-form-item>

      <el-form-item label="选择学生" prop="studentId">
        <el-select
          v-model="form.studentId"
          placeholder="请选择学生"
          style="width: 100%"
        >
          <el-option
            v-for="student in students"
            :key="student.id"
            :label="student.name"
            :value="student.id"
          />
        </el-select>
      </el-form-item>

      <el-form-item label="开始时间" prop="startTime">
        <el-date-picker
          v-model="form.startTime"
          type="datetime"
          placeholder="选择开始时间"
          style="width: 100%"
          value-format="YYYY-MM-DD HH:mm:ss"
        />
      </el-form-item>

      <el-form-item label="结束时间" prop="endTime">
        <el-date-picker
          v-model="form.endTime"
          type="datetime"
          placeholder="选择结束时间"
          style="width: 100%"
          value-format="YYYY-MM-DD HH:mm:ss"
        />
      </el-form-item>

      <el-form-item label="作业内容">
        <div class="homework-items">
          <div
            v-for="(item, index) in form.items"
            :key="index"
            class="item-row"
          >
            <el-input
              v-model="item.content"
              placeholder="输入作业内容"
              style="flex: 1"
            />
            <el-select
              v-model="item.isRequired"
              style="width: 120px; margin-left: 10px"
            >
              <el-option label="必须完成" :value="true" />
              <el-option label="非必须" :value="false" />
            </el-select>
            <el-button
              type="danger"
              size="small"
              @click="removeItem(index)"
              style="margin-left: 10px"
            >
              删除
            </el-button>
          </div>
          <el-button
            type="primary"
            size="small"
            @click="addItem"
            style="margin-top: 10px"
          >
            添加作业项
          </el-button>
        </div>
      </el-form-item>
    </el-form>

    <template #footer>
      <span class="dialog-footer">
        <el-button @click="visible = false">取消</el-button>
        <el-button type="primary" @click="submitForm" :loading="loading">
          创建作业
        </el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script setup>
import { ref, computed, onMounted, watch } from 'vue'
import { ElMessage } from 'element-plus'
import { homeworkApi } from '../api/homework'
import { studentApi } from '../api/student'

// Props
const props = defineProps({
  modelValue: {
    type: Boolean,
    default: false
  }
})

// Emits
const emit = defineEmits(['update:modelValue', 'success'])

// Reactive data
const formRef = ref()
const loading = ref(false)
const students = ref([])

const form = ref({
  title: '',
  studentId: null,
  startTime: '',
  endTime: '',
  items: [
    { content: '', isRequired: true }
  ]
})

// Computed
const visible = computed({
  get: () => props.modelValue,
  set: (val) => emit('update:modelValue', val)
})

const defaultTitle = computed(() => {
  const now = new Date()
  const date = now.toLocaleDateString('zh-CN', {
    month: 'long',
    day: 'numeric'
  })
  return `${date}家庭作业`
})

// Form validation rules
const rules = {
  title: [
    { max: 100, message: '标题长度不能超过100个字符', trigger: 'blur' }
  ],
  studentId: [
    { required: true, message: '请选择学生', trigger: 'change' }
  ],
  startTime: [
    { required: true, message: '请选择开始时间', trigger: 'change' }
  ],
  endTime: [
    { required: true, message: '请选择结束时间', trigger: 'change' }
  ]
}

// Methods
const loadStudents = async () => {
  try {
    const response = await studentApi.getAll()
    students.value = response.data || []
  } catch (error) {
    console.error('加载学生列表失败:', error)
    ElMessage.error('加载学生列表失败')
  }
}

const addItem = () => {
  form.value.items.push({ content: '', isRequired: true })
}

const removeItem = (index) => {
  if (form.value.items.length > 1) {
    form.value.items.splice(index, 1)
  } else {
    ElMessage.warning('至少需要保留一个作业项')
  }
}

const resetForm = () => {
  form.value = {
    title: '',
    studentId: null,
    startTime: '',
    endTime: '',
    items: [
      { content: '', isRequired: true }
    ]
  }
  formRef.value?.clearValidate()
}

const submitForm = async () => {
  try {
    await formRef.value.validate()

    // 验证作业内容
    const validItems = form.value.items.filter(item => item.content.trim())
    if (validItems.length === 0) {
      ElMessage.error('至少需要填写一个作业内容')
      return
    }

    // 验证时间
    if (new Date(form.value.endTime) <= new Date(form.value.startTime)) {
      ElMessage.error('结束时间必须晚于开始时间')
      return
    }

    loading.value = true

    const submitData = {
      title: form.value.title.trim() || defaultTitle.value,
      studentId: form.value.studentId,
      startTime: form.value.startTime,
      endTime: form.value.endTime,
      details: validItems.map(item => ({
        content: item.content.trim(),
        isRequired: item.isRequired
      }))
    }

    console.log('创建作业数据:', submitData)

    const response = await homeworkApi.create(submitData)

    ElMessage.success('作业创建成功')
    emit('success')
    visible.value = false

  } catch (error) {
    console.error('创建作业失败:', error)
    ElMessage.error(error.response?.data?.message || '创建作业失败')
  } finally {
    loading.value = false
  }
}

// Lifecycle
onMounted(() => {
  loadStudents()
})

// Watch for dialog open
watch(() => props.modelValue, (newVal) => {
  if (newVal) {
    // 设置默认时间
    const now = new Date()
    const tomorrow = new Date(now.getTime() + 24 * 60 * 60 * 1000)

    form.value.startTime = now.toISOString().slice(0, 19).replace('T', ' ')
    form.value.endTime = tomorrow.toISOString().slice(0, 19).replace('T', ' ')

    // 如果只有一个学生，默认选择
    if (students.value.length === 1) {
      form.value.studentId = students.value[0].id
    }
  }
})
</script>

<style scoped>
.form-tip {
  font-size: 12px;
  color: #909399;
  margin-top: 4px;
}

.homework-items {
  width: 100%;
}

.item-row {
  display: flex;
  align-items: center;
  margin-bottom: 10px;
}

.item-row:last-child {
  margin-bottom: 0;
}

.dialog-footer {
  text-align: right;
}
</style>